package com.angel.activity;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.angel.adapter.ImplePagerAdapter;
import com.angel.entity.ActivityBeanList;
import com.angel.entity.Task;
import com.angel.port.IActivity;
import com.angel.service.TaskService;
import com.angel.util.*;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/*主推活动，即登陆页面*/
public class MainActivity extends Activity implements IActivity {
    private GridView bottomBarView,topbarView;
    private LinearLayout hotBnt,weekBnt,classifyBnt,areaBnt;//底部菜单按钮
    private ViewGroup topViewGroup,pageShow;
    private ViewPager viewpager;
    private ImageView[] imageViews;
    private static final int FINSHFRESH=6;//刷新标签id
    private ProgressBar progressBar;
    private Button imageButton;
    private RelativeLayout relativeLayout;
    private MyOnClickListener myOnClickListener;
    private Context context;
    private int nowPosition;//标志当前活动处于第几张页面的位置
    private Intent intentService,startIntent;//启动service
    private HashMap<String,String> map=new HashMap<String,String>();//用于封装上传参数
    private  ActivityBeanList activityBeanList;
    private ProgressDialog progressDialog;
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.main);
		 MobclickAgent.onError(this);//自动捕获异常退出（FC ）
		context=MainActivity.this;
		progressDialog=new ProgressDialog(context);
		progressDialog.setMessage("加载数据中，请耐心等候...");
	//	progressDialog.setIcon(R.drawable.clock_icon);
		
		startIntent=getIntent();
		/*登陆数据传递*/
		String jsonData=startIntent.getStringExtra("jsonData");
		
		myOnClickListener=new MyOnClickListener();
        /*获得上方布局*/
		topViewGroup=(ViewGroup) findViewById(R.id.linerlayout);
		topViewGroup.inflate(MainActivity.this, R.layout.home_top_view, topViewGroup);
		
		/*布局上方菜单*/
		hotBnt=(LinearLayout) topViewGroup.findViewById(R.id.hot_bnt_id);
		weekBnt=(LinearLayout) topViewGroup.findViewById(R.id.week_bnt_id);
		classifyBnt=(LinearLayout) topViewGroup.findViewById(R.id.classify_bnt_id);
		areaBnt=(LinearLayout) topViewGroup.findViewById(R.id.area_bnt_id);
		hotBnt.setOnClickListener(myOnClickListener);
		weekBnt.setOnClickListener(myOnClickListener);
		classifyBnt.setOnClickListener(myOnClickListener);
		areaBnt.setOnClickListener(myOnClickListener);
		/*添加对viewpager的初始布局及事件监听*/
		viewpager=(ViewPager)topViewGroup.findViewById(R.id.viewpager);
		hotBnt.setSelected(true);
		//下载活动内容
		
	   	pageShow=(ViewGroup)topViewGroup.findViewById(R.id.viewGroup); 
		  
//		  }
		 
		  relativeLayout=(RelativeLayout)topViewGroup.findViewById(R.id.myactivity_title);
		  progressBar=(ProgressBar)relativeLayout.findViewById(R.id.progressbar);
		  imageButton=(Button)relativeLayout.findViewById(R.id.refreshimg);
		  imageButton.setOnClickListener(myOnClickListener);
		  if(jsonData!=null){//如果是登陆，启动主推活动
				layout(jsonData);
		  }
    }
   
    /*将drawable转化为Bitmap*/
    public Bitmap drawableToBitmap(Drawable dr){
    	Drawable d=dr;
    	BitmapDrawable bitDrawable=(BitmapDrawable)dr;
    	Bitmap bitmap=bitDrawable.getBitmap();
    	return bitmap;
    }
    /*对viewpager进行布局*/
    public void layout(String actiContent){
    	    Type type=new TypeToken<ActivityBeanList>(){}.getType();
    	    activityBeanList=(ActivityBeanList)BaseUtil.getEntityFromJson(actiContent,type);
    	    pageShow.removeAllViews();//先移除之前所有的ImageView,避免累加
    	    imageViews=new ImageView[activityBeanList.getList().size()];
    	    for(int i=0;i<activityBeanList.getList().size();i++){//根据当前活动主题数量布局
  			  imageViews[i]=new ImageView(MainActivity.this);
  			  imageViews[i].setLayoutParams(new LinearLayout.LayoutParams(20,20));
  			  imageViews[i].setPadding(20, 0, 20, 0);
  			  if(i==0){
  			      imageViews[i].setBackgroundResource(R.drawable.dotchecked);    	  
  			      }else{
  			      imageViews[i].setBackgroundResource(R.drawable.dotdefault);    	 
  			      }
  			    pageShow.addView(imageViews[i]);
  		  }
    	    
    	  viewpager.setOnPageChangeListener(new ImpleOnPageChangeListener());
		  viewpager.setAdapter(new ImplePagerAdapter(MainActivity.this,activityBeanList.getList()));
		  imageButton.setVisibility(View.VISIBLE);
		  progressBar.setVisibility(View.GONE);
    }
    /*改变其他row的背景颜色*/
    public void changeBackground(AdapterView<?> parent, View view, int position){
    	for(int i=0;i<4;i++){
			if(i==position){
				view.setBackgroundResource(R.drawable.bt_menu_press_bg);
			}else{
				View v=parent.getChildAt(i);
				v.setBackgroundResource(R.drawable.channelgallery_bg);
			}
		}
    }
    /*用于按钮监听*/
    class MyOnClickListener implements OnClickListener{
				@Override
				public void onClick(View v) {
					int id=v.getId();
					String userId=UserInfoUtil.getValue(context,"userId", "");
					
					if(id==R.id.refreshimg){
						imageButton.setVisibility(View.GONE);
						progressBar.setVisibility(View.VISIBLE);
						//获取当前活动类型Id，作为请求参数
						map.put("userId",userId );
						map.put("activitiyKindId", activityBeanList.getActivitiyKindId());
					}else if(id==R.id.hot_bnt_id){
						map.put("userId",userId );
						map.put("activitiyKindId", "1");
						hotBnt.setSelected(true);
						weekBnt.setSelected(false);
						classifyBnt.setSelected(false);
						areaBnt.setSelected(false);
					}else if(id==R.id.week_bnt_id){
						map.put("userId",userId );
						map.put("activitiyKindId", "2");
						hotBnt.setSelected(false);
						weekBnt.setSelected(true);
						classifyBnt.setSelected(false);
						areaBnt.setSelected(false);
					}else if(id==R.id.classify_bnt_id){
						map.put("userId",userId );
						map.put("activitiyKindId", "3");
						hotBnt.setSelected(false);
						weekBnt.setSelected(false);
						classifyBnt.setSelected(true);
						areaBnt.setSelected(false);
					}else if(id==R.id.area_bnt_id){
						map.put("userId",userId );
						map.put("activitiyKindId", "4");
						hotBnt.setSelected(false);
						weekBnt.setSelected(false);
						classifyBnt.setSelected(false);
						areaBnt.setSelected(true);
					}
					progressDialog.show();//显示进度条对话框
				BaseUtil.startService(Task.MAIN_ACITITY,MainActivity.this,map);
				}
        }
    /*viewpage 滑动翻页监听*/
  class ImpleOnPageChangeListener implements OnPageChangeListener{
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
	
		@Override
		public void onPageSelected(int arg0) {
			for(int i=0;i<activityBeanList.getList().size();i++){
			  imageViews[i].setBackgroundResource(R.drawable.dotdefault);
			  if(i==arg0){
				  imageViews[i].setBackgroundResource(R.drawable.dotchecked);
			  }
			}
//			View v=findViewById(arg0);
		}
    }
  
	@Override
	public void init() {
	}
	@Override
	public void refresh(Object... params) {
		String isSucess=BaseUtil.getValueFromJSON((String)params[0]);
		
		 if(isSucess.equals("2")){
			 BaseUtil.makeToast(MainActivity.this, "对不起,网络连接超时,请稍后重试...");
			 progressDialog.dismiss();
			 return ;
		}
				progressDialog.cancel();//关闭对话框
				layout(params[0]+"");
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			BaseUtil.showExitDialog(this);
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onResume() {
		Log.i("MainActivity","MainActivity-->onResume");
		super.onResume();
		MobclickAgent.onResume(this);
	}
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
}